﻿#include "Create_Model.h"
#include <QDebug>
Create_Model::Create_Model()
{

}
void Create_Model::C_Model(HObject Img,HTuple WindowHandle,HTuple SavePath)
{
    HTuple Row1, Column1, Row2, Column2,Length1,Length2;
	HObject Rectangle, ImageReduced, ModelContours, ContoursAffineTrans, ImageRotate, Contours, Region, Region2;
    HTuple ModelID,Row, Column, Angle, Score,HomMat2D,Phi;
    try
    {
        SetColor(WindowHandle,"red");
        DrawRectangle1(WindowHandle, &Row1, &Column1, &Row2, &Column2);

        Threshold (Img, &Region, 0, 200);
        Connection(Region,&Region);
        SelectShapeStd(Region, &Region, "max_area", 70);
        SmallestRectangle2 (Region, &Row, &Column, &Phi, &Length1, &Length2);
        if(Phi>PI/2)
        {
            RotateImage (Img, &ImageRotate, (PI/2-Phi)*180/PI, "constant");
        }
        else
        {
            RotateImage (Img, &ImageRotate, (-Phi)*180/PI, "constant");

        }

        GenRectangle1(&Rectangle, Row1, Column1, Row2, Column2);
	
	
		ReduceDomain(ImageRotate, Rectangle, &ImageReduced);
		Threshold(ImageReduced, &Region2, 0, 200);
		GenContourRegionXld(Region2, &Contours, "border");
		CreateShapeModelXld(Contours, "auto", HTuple(-180).TupleRad(), HTuple(180).TupleRad(),
			"auto", "auto", "ignore_local_polarity", 5, &ModelID);
		GetShapeModelContours(&ModelContours, ModelID, 1);
		FindShapeModel(ImageReduced, ModelID, HTuple(-180).TupleRad(), HTuple(180).TupleRad(),
			0.5, 1, 0.5, "least_squares", 0, 0.9, &Row, &Column, &Angle, &Score);
		VectorAngleToRigid(0, 0, 0, Row, Column, Angle + Phi, &HomMat2D);
		AffineTransContourXld(ModelContours, &ContoursAffineTrans, HomMat2D);
		DispObj(ContoursAffineTrans, WindowHandle);
		WriteShapeModel(ModelID, SavePath);

     
    }
    catch(HException ex)
    {
        qDebug() << ex.ErrorMessage();
    }

}
